class TrackController < ApplicationController

  before_filter :sys_before_log

  #获取所有组队的信息
  def getTracks
    total = Track.count
    tracks = Track.findPage params[:start].to_i,params[:limit].to_i
    jsonStr="{track:"+tracks.to_json()+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  def getAllTracks
    forCBB = params[:for_cbb]
    if forCBB.nil?
      total = Track.count
      tracks = Track.all
    else
      tracks = Track.where("is_locked = 0")
      total = tracks.length
    end
    
    jsonStr="{track:"+tracks.to_json()+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  def create
    begin
      track = Track.find_by_track_name params[:track_name]
      if track != nil
        info = '股道已存在，请更换！'
      else
        track = Track.new
        track.track_name = params[:track_name]
        track.device_id = params[:device_id].to_s
        track.save!
        info = 'success'
      end
    rescue Exception => e
      logger.info e
      info = '创建异常'
    end

    result = "{success:true,info:\"#{info}\"}"
    render :text => result,:layout => false
  end

  #锁定或解锁，只允许锁定。
  def doLock
    ids= params[:id][1..params[:id].length-2].split(',')
    for id in ids
      track = Track.find(id)
      if track.is_locked == 1
        track.is_locked = 0
      else
        track.is_locked = 1
      end
      track.save!
    end
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #获取指定组队的信息
  def edit
    track = Track.find(params[:id])
    jsonStr = track.to_json()
    render :text=>jsonStr,:layout=>false
  end

  def update
    begin
      track = Track.find(params[:id])
      if track.track_name == params[:track_name].to_s
        track.device_id = params[:device_id].to_s
        track.save
        info = 'success'
      else
        trackName = Track.find_by_track_name params[:track_name]
        if trackName == nil
          track.track_name = params[:track_name]
          track.device_id = params[:device_id].to_s
          track.save
          info = 'success'
        else
          info = '该股道已存在，请更换！'
        end
      end
    rescue Exception=>e
      logger.info e
      info = '更新异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

end
